/*
 * @Description:
 * @Author: Junhuang
 * @Date: 2022-06-29 16:54:29
 * @LastEditTime: 2022-08-03 11:31:05
 * @LastEditors: Junhuang
 * @Reference:
 */
'use strict';

const Controller = require('egg').Controller;
const md5 = require('md5');
class LiveController extends Controller {
  async index() {
    const { ctx, app } = this;
    const res = await app.model.Live.findAll({
      include: [
        {
          model: app.model.User,
          attributes: [[ 'id', 'user_id' ], 'username', 'nickname', 'avatar' ],
        },
      ],
    });
    return ctx.apiSuccesss(res);
  }

  // 创建直播间
  async save() {
    const { ctx, app } = this;
    const user_id = ctx.authUser.id;

    const {
      title, cover, description, config,
    } = ctx.request.body;

    // 参数验证
    ctx.validate({
      title: {
        required: true,
        type: 'string',
        desc: '直播间标题',
      },
      cover: {
        required: false,
        type: 'string',
        desc: '直播间封面',
      },
    });

    console.log('config=', config);

    // 生成唯一id
    const key = ctx.randomString(20);

    const res = await app.model.Live.create({
      title,
      cover,
      key,
      user_id,
      description,
      config,
      status: 1,
    });

    if (!res) {
      return ctx.apiFail('创建直播间失败');
    }

    const live = await app.model.Live.findOne({
      where: {
        id: res.id,
      },
      include: [{
        model: app.model.User,
        attributes: [ 'id', 'username', 'avatar', 'nickname', 'coin' ],
      }],
    });

    // 生成签名
    const sign = this.sign(key);

    return ctx.apiSuccesss({
      data: live,
      sign,
    });
  }

  // 生成签名
  sign(key) {
    const { app } = this;
    const secret = app.config.mediaServer.auth.secret;
    const expire = parseInt((Date.now() + 30 * 24 * 60 * 60 * 1000) / 1000);
    const hashValue = md5(`/live/${key}-${expire}-${secret}`);
    return `${expire}-${hashValue}`;
  }


  // 修改直播间状态
  async changeStatus() {
    const { ctx, app } = this;
    const user_id = ctx.authUser.id;
    const { status } = ctx.request.body;

    // 参数验证
    ctx.validate({
      id: {
        type: 'int',
        required: true,
        desc: '直播间ID',
      },
      // 0:未开始，1:正在直播，2:暂停直播, 3:直播结束
      status: {
        type: 'int',
        required: true,
        desc: '直播间状态',
      },
    });
    const id = ctx.params.id;

    const live = await app.model.Live.findOne({
      where: {
        id,
        user_id,
      },
    });

    if (!live) {
      return ctx.apiFail('该直播间不存在');
    }

    if (live.status === 3) {
      return ctx.apiFail('该直播间已结束');
    }

    live.status = status;
    await live.save();

    return ctx.apiSuccesss(live);
  }

  // 直播间列表，分页
  async list() {
    const { ctx, app } = this;
    let limit = 10;
    let user_id = 0;
    if (ctx.query) {
      if (ctx.query.limit) {
        limit = parseInt(ctx.query.limit);
      }
      if (ctx.query.user_id) {
        user_id = parseInt(ctx.query.user_id);
      }
    }
    const where = {};
    if (user_id) {
      where.user_id = user_id;
    }
    ctx.validate({
      page: {
        required: true,
        desc: '页码',
        type: 'int',
      },
    });

    const page = ctx.params.page;

    const offset = (page - 1) * limit;

    const rows = await app.model.Live.findAll({
      where,
      limit,
      offset,
      order: [[ 'id', 'desc' ]],
    });

    console.log(JSON.stringify(rows));
    return ctx.apiSuccesss(rows);
  }

  async read() {
    const { ctx, app } = this;

    ctx.validate({
      id: {
        required: true,
        desc: '直播间ID',
        type: 'int',
      },
    });

    const id = ctx.params.id;

    const live = await app.model.Live.findOne({
      where: {
        id,
      },
      include: [{
        model: app.model.User,
        attributes: [ 'id', 'username', 'avatar', 'nickname', 'coin' ],
      }],
    });

    if (!live) {
      return ctx.apiFail('该直播间不存在');
    }

    // 生成签名
    let sign = null;

    // 直播未结束
    if (live.status !== 3) {
      sign = this.sign(live.key);
    }

    // 获取当前直播间最新3个用户
    let liver_user = await app.model.LiveUser.findAll({
      where: {
        live_id: id,
      },
      include: [{
        model: app.model.User,
        attributes: [ 'id', 'username', 'avatar', 'nickname', 'coin' ],
      }],
      order: [[ 'id', 'DESC' ]],
      limit: 3,
    });

    if (liver_user) {
      liver_user = JSON.parse(JSON.stringify(liver_user));
      liver_user.forEach(user => {
        user.username = user.user.username;
        user.avatar = user.user.avatar;
        user.nickname = user.user.nickname;
        user.coin = user.user.coin;
        delete user.user;
      });
    }

    return ctx.apiSuccesss({
      live,
      sign,
      liver_user,
    });
  }

  // 修改直播间状态
  async changeLiveConfig() {
    const { ctx, app } = this;
    const user_id = ctx.authUser.id;

    // 参数验证
    ctx.validate({
      id: {
        type: 'int',
        required: true,
        desc: '直播间ID',
      },
      config: {
        type: 'string',
        required: true,
        desc: '配置信息',
      },
    });

    const { config } = ctx.request.body;
    const id = ctx.params.id;

    const live = await app.model.Live.findOne({
      where: {
        id,
        user_id,
      },
    });

    if (!live) {
      return ctx.apiFail('该直播间不存在');
    }

    if (live.status === 3) {
      return ctx.apiFail('该直播间已结束');
    }

    live.config = config;
    await live.save();

    return ctx.apiSuccesss(live);
  }
}

module.exports = LiveController;
